/**
 * Tracks all changes/annotations related to a given posting such as changing the phone number,
 * email address, or geo-location for the posting. Any time a posting is annotated, it is
 * automatically added to the hard cache
 * @author birdeau@yahoo.com
 */
jsx3.lang.Class.defineClass("gicx.Audit", null, [], function(Audit,Audit_prototype) {


  /**
   * main method
   */
  Audit_prototype.init = function() {
    this.jsxsuper();
  };


  /**
   * Inserts note when a skype call is made
   * @param intNumber {int}
   */
  Audit.phone = function(intNumber) {
    Audit.insertNote(null,"Phone","Called " + intNumber);
  };


  /**
   * Inserts note when an email is sent
   * @param strEmail {String} email address
   * @param strSubject {String} email subject
   */
  Audit.email = function(strEmail,strSubject) {
    Audit.insertNote(null,"Email","Emailed " + strEmail + " regarding " + (strSubject?window.unescape(strSubject):''));
  };


  /**
   * Inserts note related to the active posting
   * @param strNoteId {String} unique ID for the note
   * @param TYPE {String} one of: Email or Phone
   * @param strDescription {String} content for the note
   */
  Audit.insertNote = function(strNoteId,TYPE,strDescription) {
    var m = gicx.APP.getJSXByName("mtxNote");
    var o = {jsxid:strNoteId?strNoteId:(new Date()).valueOf(),activity:TYPE,description:strDescription};
    m.insertRecord(o,null,false);
    m.repaint();
    Audit.cache();
  };


  /**
   * Deletes the specific note
   * @param strId {String} unique ID for the note
   */
  Audit.deleteNote = function(strId) {
    gicx.APP.getJSXByName("mtxNote").deleteRecord(strId, true);
    Audit.onSelectNote();
    Audit.cache();
  };


  /**
   * Saves any edits made to the annotations table (the notes table).
   */
  Audit.cache = function() {
    var objRecord = gicx.Posting.getActiveRecord();
    if(objRecord) {
      var objAuditNode = objRecord.selectSingleNode("audit");
      if(objAuditNode) {
        objAuditNode.removeChildren();
      } else {
        objAuditNode = objRecord.createNode(jsx3.xml.Entity.TYPEELEMENT,"audit");
        objRecord.appendChild(objAuditNode);
      }

      //loop through all controls to read the rolodex values from the UI and back into the cache (but only if not empty)
      var objM = gicx.APP.getJSXByName("mtxNote");
      var objNodes = objM.getXML().selectNodes("//record");
      for(var i=0;i<objNodes.size();i++) {
        var objClone = objNodes.get(i).cloneNode(true);
        objClone.removeAttribute("jsxselected");
        objAuditNode.appendChild(objClone);
      }

      //favorite the posting or update the existing favorite (if already a favorite); NOTE: searchHistory is the 'hard' cache where the favorites are stored
      var bWasFavorited = gicx.Posting.favorite(objRecord.getAttribute("jsxid"));
      jsx3.log("A: " + objRecord);
      if(!bWasFavorited)
        gicx.Cache.setRecord("searchHistory", objRecord, gicx.Cache.getDocument("searchHistory").selectSingleNode("//favorites"));
    }
  };


  /**
   * Called when a posting is deactivated; does general cleanup (resetting of UI)
   * @param objEvent {Object}
   */
  Audit.onDeactivatePosting = function(objEvent) {
    gicx.APP.getJSXByName("panAudit").showMask("<div style='position:absolute;left:160px;top:40px;width:100%;text-align:left;color:#efeff0;white-space:no-wrap;'>(loading...)</div>");
    var objM = gicx.APP.getJSXByName("mtxNote");
    objM.resetXmlCacheData();
    objM.repaintData();
  };


  /**
   * Called when a posting is activated; populates the email, phone, and geo-address fiels
   * @param objEvent {Object} hash with named field, target (the tab that was activated)
   */
  Audit._delay;
  Audit.onActivatePosting = function(objEvent) {
    window.clearTimeout(Audit._delay);
    Audit._delay = window.setTimeout(function() {Audit._onActivatePosting(objEvent);},1000);
  };


  //called via a timeout delay to throttle CPU spike if user switches tabs too quickly
  Audit._onActivatePosting = function(objEvent) {
    gicx.APP.getJSXByName("panAudit").hideMask();
    var objTab = objEvent.target;
    if(objTab) {
      var objRecord = gicx.Cache.getRecord("searchHistory",objTab.postingurl);
      if(!objRecord) objRecord = gicx.Cache.getRecord("_searchHistory",objTab.postingurl);
      if(objRecord) {
        //create and populate the controls necessary to show the user's saved emails and phone numbers for the given posting
        var objAuditNode = objRecord.selectSingleNode("audit");
        var objM = gicx.APP.getJSXByName("mtxNote");
        if(objAuditNode) {
          var i = 0;
          var iterator = objAuditNode.selectNodeIterator("record");
          //throttle at three for performance reasons
          while(iterator.hasNext() && i < 3) {
            var objNode = iterator.next();
            objM.insertRecordNode(objNode.cloneNode(true));
            i++;
          }
        }
      } else {
        jsx3.log("error getting from data cache: " + objTab.postingurl);
      }
    }
  };


  /**
   * Allows user to create/edit a notation for the active posting
   * @param strNoteId {String}
   */
  Audit.showNoteEditor = function(strNoteId) {
    var objM = gicx.APP.getJSXByName("panAudit");
    var objDlg = objM.loadAndCache("components/AuditNoteEditor.xml",false);
    var objP = objM.getAbsolutePosition();
    objDlg.setWidth(objP.W - 40);
    objDlg.setHeight(objP.H - 40);

    if(strNoteId) {
      var m = gicx.APP.getJSXByName("mtxNote");
      var objRec = m.getRecord(strNoteId);
      var mf = jsx3.util.DateFormat.getDateTimeInstance(jsx3.util.DateFormat.SHORT,jsx3.util.DateFormat.SHORT);
      var strDate = mf.format(objRec.jsxid-0);
      var strType = objRec.activity;
      var strDesc = objRec.description
      var intEnabled = 1;
      objDlg.noteid = objRec.jsxid;
    } else {
      var strDate = '';
      var strType;
      var strDesc = '';
      var intEnabled = 0;
      delete objDlg.noteid;
    }

    gicx.APP.getJSXByName("txtNoteDate").setValue(strDate);
    if(strType)
      gicx.APP.getJSXByName("selNoteType").setValue(strType);
    gicx.APP.getJSXByName("txtNoteDescription").setValue(strDesc);
    objM.paintChild(objDlg);
    gicx.APP.getJSXByName("txtNoteDescription").focus();
  };


  /**
   * Enables/disables the 'update' button when a notation is selected
   * @param strNoteId {String}
   */
  Audit.onSelectNote = function(strNoteId) {
    gicx.APP.getJSXByName("btnNoteUpdate").setEnabled(strNoteId?1:0,true);
  };


  /**
   * Called when user tries to save any manual edits to a given note
   * @param objEvent {Object} hash with named fields: date, activity, description
   */
  Audit.update = function(objEvent) {
    var strId = gicx.Posting.getActive().getName();
    var objPost = gicx.Cache.getDocument("searchHistory").selectSingleNode("//record[@jsxid='" + strId + "']");
    if(objPost) {
      var objAudit = objPost.selectSingleNode("audit");
      if(!objAudit) {
        var objAudit = objPost.createNode(jsx3.xml.Entity.TYPEELEMENT,"audit");
        objPost.appendChild(objAudit);
      }
      objAudit.setAttribute("date",objEvent.date);
      objAudit.setAttribute("activity",objEvent.activity);
      objAudit.setAttribute("description",objEvent.description);
    }
  };

});


//subscribe handler functions to relevant application events
gicx.APP.subscribe("POSTING_WAS_ACTIVATED",gicx.Audit.onActivatePosting);
gicx.APP.subscribe("POSTING_WAS_DEACTIVATED",gicx.Audit.onDeactivatePosting);




